package com.lxinet.jeesns.modules.wechat.service.impl;

import com.blade.kit.DateKit;
import com.blade.kit.FileKit;
import com.blade.kit.StringKit;
import com.blade.kit.http.HttpRequest;
import com.blade.kit.json.JSON;
import com.blade.kit.json.JSONArray;
import com.blade.kit.json.JSONKit;
import com.blade.kit.json.JSONObject;
import com.lxinet.jeesns.modules.wechat.entity.*;
import com.lxinet.jeesns.modules.wechat.exception.WechatException;
import com.lxinet.jeesns.modules.wechat.listener.WechatListener;
import com.lxinet.jeesns.modules.wechat.service.WechatService;
import com.lxinet.jeesns.modules.wechat.utils.Constant;
import com.lxinet.jeesns.modules.wechat.utils.Matchers;
import com.lxinet.jeesns.modules.wechat.utils.PingUtil;
import com.lxinet.jeesns.utils.JedisUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.lxinet.jeesns.modules.wechat.utils.FileUtil.getSendBase64ByImgFile;
import static com.lxinet.jeesns.modules.wechat.utils.MD5Util.getMd5ByFile;
import static com.lxinet.jeesns.modules.wechat.utils.MD5Util.string2MD5;

@Service("wechatService")
public class WechatServiceImpl implements WechatService {

	private static final Logger LOGGER = LoggerFactory.getLogger(WechatService.class);
	private Jedis jedis = JedisUtil.getInstance().getJedis();

	public WechatServiceImpl(){
		System.setProperty("https.protocols", "TLSv1");
		System.setProperty("jsse.enableSNIExtension", "false");
	}

	// 茉莉机器人
//	private Robot robot = new MoLiRobot();

	@Resource
	private WechatRecordServiceImpl wechatRecordService;

	@Resource
	private WechatMetaServiceImpl wechatMetaService;

	@Resource
	private WechatAutoReplyServiceImpl wechatAutoReplyService;

	@Resource
	private WechatReplyConfigServiceImpl wechatReplyConfigService;


	/**
	 * 获取联系人
	 */
	@Override
	public WechatContact getContact(WechatMeta wechatMeta) {
		String url = wechatMeta.getBase_uri() + "/webwxgetcontact?pass_ticket=" + wechatMeta.getPass_ticket() + "&skey="
				+ wechatMeta.getSkey() + "&r=" + DateKit.getCurrentUnixTime();

		JSONObject body = new JSONObject();
		body.put("BaseRequest", wechatMeta.getBaseRequest());

		HttpRequest request = HttpRequest.post(url).contentType("application/json;charset=utf-8")
				.header("Cookie", wechatMeta.getCookie()).send(body.toString());
		
		LOGGER.debug(request.toString());
		String res = request.body();
		request.disconnect();

		if (StringKit.isBlank(res)) {
			throw new WechatException("获取联系人失败");
		}
		
		LOGGER.debug(res);
		
		WechatContact wechatContact = new WechatContact();
		try {
			JSONObject jsonObject = JSONKit.parseObject(res);
			JSONObject BaseResponse = jsonObject.get("BaseResponse").asJSONObject();
			if (null != BaseResponse) {
				int ret = BaseResponse.getInt("Ret", -1);
				if (ret == 0) {
					JSONArray memberList = jsonObject.get("MemberList").asArray();
					JSONArray contactList = new JSONArray();
					JSONArray groupChatList = new JSONArray();

					if (null != memberList) {
						for (int i = 0, len = memberList.size(); i < len; i++) {
							JSONObject contact = memberList.get(i).asJSONObject();
							// 公众号/服务号
							if (contact.getInt("VerifyFlag", 0) != 0) {
								continue;
							}
							// 特殊联系人
							if (Constant.FILTER_USERS.contains(contact.getString("UserName"))) {
								continue;
							}
							// 群聊
							if (contact.getString("UserName").indexOf("@@") != -1) {
								groupChatList.add(contact);
								continue;
							}
							// 自己
							if (contact.getString("UserName").equals(wechatMeta.getUser().getString("UserName"))) {
								continue;
							}
							contactList.add(contact);
						}

						wechatContact.setContactList(contactList);
						wechatContact.setMemberList(memberList);
						wechatContact.setGroupChatList(groupChatList);
						this.getGroup(wechatMeta, wechatContact);
						
						return wechatContact;
					}
				}
			}
		} catch (Exception e) {
			throw new WechatException(e);
		}
		return null;
	}

	private void getGroup(WechatMeta wechatMeta, WechatContact wechatContact) {
		String url = wechatMeta.getBase_uri() + "/webwxbatchgetcontact?type=ex&pass_ticket=" + wechatMeta.getPass_ticket() + "&skey="
				+ wechatMeta.getSkey() + "&r=" + DateKit.getCurrentUnixTime();

		JSONObject body = new JSONObject();
		body.put("BaseRequest", wechatMeta.getBaseRequest());

		HttpRequest request = HttpRequest.post(url).contentType("application/json;charset=utf-8")
				.header("Cookie", wechatMeta.getCookie()).send(body.toString());
		
		LOGGER.debug(request.toString());
		String res = request.body();
		request.disconnect();

		if (StringKit.isBlank(res)) {
			throw new WechatException("获取群信息失败");
		}
		
		LOGGER.debug(res);
		
		try {
			JSONObject jsonObject = JSONKit.parseObject(res);
			JSONObject BaseResponse = jsonObject.get("BaseResponse").asJSONObject();
			if (null != BaseResponse) {
				int ret = BaseResponse.getInt("Ret", -1);
				if (ret == 0) {
					JSONArray memberList = jsonObject.get("MemberList").asArray();
					JSONArray contactList = new JSONArray();
					
					if (null != memberList) {
						for (int i = 0, len = memberList.size(); i < len; i++) {
							JSONObject contact = memberList.get(i).asJSONObject();
							// 公众号/服务号
							if (contact.getInt("VerifyFlag", 0) == 8) {
								continue;
							}
							// 特殊联系人
							if (Constant.FILTER_USERS.contains(contact.getString("UserName"))) {
								continue;
							}
							// 群聊
							if (contact.getString("UserName").indexOf("@@") != -1) {
								continue;
							}
							// 自己
							if (contact.getString("UserName").equals(wechatMeta.getUser().getString("UserName"))) {
								continue;
							}
							contactList.add(contact);
						}
						
						wechatContact.setContactList(contactList);
						wechatContact.setMemberList(memberList);
					}
				}
			}
		} catch (Exception e) {
			throw new WechatException(e);
		}
	}

	/**
	 * 获取UUID
	 */
	@Override
	public String getUUID() {
		HttpRequest request = HttpRequest.get(Constant.JS_LOGIN_URL, true, "appid", "wx782c26e4c19acffb", "fun", "new",
				"lang", "zh_CN", "_", DateKit.getCurrentUnixTime());
		
		String res = request.body();
		request.disconnect();

		if (StringKit.isNotBlank(res)) {
			String code = Matchers.match("window.QRLogin.code = (\\d+);", res);
			if (null != code) {
				if (code.equals("200")) {
					return Matchers.match("window.QRLogin.uuid = \"(.*)\";", res);
				} else {
					throw new WechatException("错误的状态码: " + code);
				}
			}
		}
		throw new WechatException("获取UUID失败");
	}

	/**
	 * 打开状态提醒
	 */
	@Override
	public void openStatusNotify(WechatMeta wechatMeta) {

		String url = wechatMeta.getBase_uri() + "/webwxstatusnotify?lang=zh_CN&pass_ticket=" + wechatMeta.getPass_ticket();

		JSONObject body = new JSONObject();
		body.put("BaseRequest", wechatMeta.getBaseRequest());
		body.put("Code", 3);
		body.put("FromUserName", wechatMeta.getUser().getString("UserName"));
		body.put("ToUserName", wechatMeta.getUser().getString("UserName"));
		body.put("ClientMsgId", DateKit.getCurrentUnixTime());

		HttpRequest request = HttpRequest.post(url).contentType("application/json;charset=utf-8")
				.header("Cookie", wechatMeta.getCookie()).send(body.toString());

		LOGGER.debug("" + request);
		String res = request.body();
		request.disconnect();

		if (StringKit.isBlank(res)) {
			throw new WechatException("状态通知开启失败");
		}

		try {
			JSONObject jsonObject = JSONKit.parseObject(res);
			JSONObject BaseResponse = jsonObject.get("BaseResponse").asJSONObject();
			if (null != BaseResponse) {
				int ret = BaseResponse.getInt("Ret", -1);
				if (ret != 0) {
					throw new WechatException("状态通知开启失败，ret：" + ret);
				}
			}
		} catch (Exception e) {
			throw new WechatException(e);
		}
	}

	/**
	 * 微信初始化
	 */
	@Override
	public void wxInit(WechatMeta wechatMeta) {
		String url = wechatMeta.getBase_uri() + "/webwxinit?r=" + DateKit.getCurrentUnixTime() + "&pass_ticket="
				+ wechatMeta.getPass_ticket() + "&skey=" + wechatMeta.getSkey();

		JSONObject body = new JSONObject();
		body.put("BaseRequest", wechatMeta.getBaseRequest());

		HttpRequest request = HttpRequest.post(url).contentType("application/json;charset=utf-8")
				.header("Cookie", wechatMeta.getCookie()).send(body.toString());
		
		LOGGER.debug("" + request);
		String res = request.body();
		request.disconnect();

		if (StringKit.isBlank(res)) {
			throw new WechatException("微信初始化失败");
		}

		try {
			JSONObject jsonObject = JSONKit.parseObject(res);
			if (null != jsonObject) {
				JSONObject BaseResponse = jsonObject.get("BaseResponse").asJSONObject();
				if (null != BaseResponse) {
					int ret = BaseResponse.getInt("Ret", -1);
					if (ret == 0) {
						wechatMeta.setSyncKeyWord(jsonObject.get("SyncKey").asJSONObject());
						wechatMeta.setUser(jsonObject.get("User").asJSONObject());

						StringBuffer synckey = new StringBuffer();
						JSONArray list = wechatMeta.getSyncKeyWord().get("List").asArray();
						for (int i = 0, len = list.size(); i < len; i++) {
							JSONObject item = list.get(i).asJSONObject();
							synckey.append("|" + item.getInt("Key", 0) + "_" + item.getInt("Val", 0));
						}
						wechatMeta.setSynckey(synckey.substring(1));
					}
				}
			}
		} catch (Exception e) {
		}
	}
	
	/**
	 * 选择同步线路
	 */
	@Override
	public void choiceSyncLine(WechatMeta wechatMeta) {
		boolean enabled = false;
		for(String syncUrl : Constant.SYNC_HOST){
//			System.out.println("syncUrl:"+syncUrl+"---------------");
			int[] res = this.syncCheck(syncUrl, wechatMeta);
			if(res[0] == 0){
				String url = "https://" + syncUrl + "/cgi-bin/mmwebwx-bin";
				wechatMeta.setWebpush_url(url);
				wechatMetaService.update(wechatMeta);//更新头部信息
				LOGGER.info("选择线路：[{}]", syncUrl);
				enabled = true;
				break;
			}
		}
		if(!enabled){
			System.out.println("同步线路不通畅");
			//throw new WechatException("同步线路不通畅");
		}
	}
	
	/**
	 * 检测心跳
	 */
	@Override
	public int[] syncCheck(WechatMeta wechatMeta){
		return this.syncCheck(null, wechatMeta);
	}
	
	/**
	 * 检测心跳
	 */
	private int[] syncCheck(String url, WechatMeta meta){

		// 如果网络中断，休息10秒
		if(PingUtil.netIsOver()){
			try {
				TimeUnit.SECONDS.sleep(10);
			} catch (Exception e){
				LOGGER.error("", e);
			}
		}

		if(null == url){
			url = meta.getWebpush_url() + "/synccheck";
		} else{
			url = "https://" + url + "/cgi-bin/mmwebwx-bin/synccheck";
		}
		
		JSONObject body = new JSONObject();
		body.put("BaseRequest", meta.getBaseRequest());
		
		HttpRequest request = HttpRequest
				.get(url, true, "r", DateKit.getCurrentUnixTime() + StringKit.getRandomNumber(5), "skey",
						meta.getSkey(), "uin", meta.getWxuin(), "sid", meta.getWxsid(), "deviceid",
						meta.getDeviceId(), "synckey", meta.getSynckey(), "_", System.currentTimeMillis())
				.header("Cookie", meta.getCookie());

		LOGGER.debug(request.toString());
		
		String res = request.body();
		request.disconnect();

		int[] arr = new int[]{-1, -1};
		if (StringKit.isBlank(res)) {
			return arr;
		}
		
		String retcode = Matchers.match("retcode:\"(\\d+)\",", res);
		String selector = Matchers.match("selector:\"(\\d+)\"}", res);
		if (null != retcode && null != selector) {
			arr[0] = Integer.parseInt(retcode);
			arr[1] = Integer.parseInt(selector);
			return arr;
		}
		return arr;
	}

	/**
	 * 处理消息
	 */
	@Override
	public void handleMsg(WechatMeta wechatMeta, JSONObject data) {
		if (null == data) {
			return;
		}

		JSONArray AddMsgList = data.get("AddMsgList").asArray();
		
		for (int i = 0, len = AddMsgList.size(); i < len; i++) {
			LOGGER.info("你有新的消息，请注意查收");
			JSONObject msg = AddMsgList.get(i).asJSONObject();
			int msgType = msg.getInt("MsgType", 0);
			String name = getUserRemarkName(wechatMeta,msg.getString("FromUserName"));
			String content = msg.getString("Content");
			
			if (msgType == 51) {
				LOGGER.info("成功截获微信初始化消息");
			} else if (msgType == 1) {
				if (Constant.FILTER_USERS.contains(msg.getString("ToUserName"))) {
					continue;
				} else if (msg.getString("FromUserName").equals(wechatMeta.getUser().getString("UserName"))) {
					continue;
				} else if (msg.getString("ToUserName").indexOf("@@") != -1) {
					String[] peopleContent = content.split(":<br/>");
					LOGGER.info("|" + name + "| " + peopleContent[0] + ":\n" + peopleContent[1].replace("<br/>", "\n"));
				} else {
					try{
						String msgId = msg.getString("MsgId");
						LOGGER.info(name + ": " + content);
						WechatRecord wechatRecord = new WechatRecord();
						wechatRecord.setFormusername(getNickNameByName(wechatMeta,msg.getString("FromUserName")));
						wechatRecord.setTousername(getNickNameByName(wechatMeta,msg.getString("ToUserName")));
						wechatRecord.setMsgid(msgId);
						wechatRecord.setType(msgType);
						wechatRecord.setCreatetime(new Date());
						wechatRecord.setFlag(1);
						wechatRecord.setWxuin(wechatMeta.getWxuin());
						wechatRecord.setContent(content);
						WechatRecord red = wechatRecordService.findByCondition(wechatRecord.getFormusername(),wechatRecord.getTousername(),msgId);
						if(red==null){
							wechatRecordService.save(wechatRecord);
							if(wechatReplyConfigService.findByWXuin(wechatMeta.getWxuin()).getFlag()==1){
								WechatAutoReply wechatAutoReply = wechatAutoReplyService.findByKey(content,wechatMeta.getWxuin());
								if(wechatAutoReply!=null){
									String ans = wechatAutoReply.getReply();
									webwxsendmsg(wechatMeta, ans, msg.getString("FromUserName"));
									LOGGER.info("自动回复 " + ans);
									WechatRecord wr = new WechatRecord();
									wr.setFormusername(getNickNameByName(wechatMeta,msg.getString("FromUserName")));
									wr.setTousername(getNickNameByName(wechatMeta,msg.getString("ToUserName")));
									wr.setType(1);
									wr.setCreatetime(new Date());
									wr.setFlag(1);
									wr.setWxuin(wechatMeta.getWxuin());
									wr.setContent(content);
									wechatRecordService.save(wr);
								}
							}
						}
					}catch (Exception e){
						System.out.print("处理消息出现异常！");
						System.out.print(e.getMessage());

					}
				}
			} else if (msgType == 3) {
				String imgDir = "./img";
				String msgId = msg.getString("MsgId");
				String sendBase64="";
				try {
					 sendBase64=getSendBase64ByImgFile(wechatMeta.getCookie().toString(),msgId);
				} catch (IOException e) {
					e.printStackTrace();
				}


				WechatRecord wechatRecord = new WechatRecord();
				wechatRecord.setFormusername(getNickNameByName(wechatMeta,msg.getString("FromUserName")));
				wechatRecord.setTousername(getNickNameByName(wechatMeta,msg.getString("ToUserName")));
				wechatRecord.setMsgid(msgId);
				wechatRecord.setType(msgType);
				wechatRecord.setCreatetime(new Date());
				wechatRecord.setFlag(1);
				wechatRecord.setWxuin(wechatMeta.getWxuin());
				String tempcontent="<img style='width:48px;height:48px;' src='"+sendBase64+" '/>";
				wechatRecord.setContent(tempcontent);
				WechatRecord red = wechatRecordService.findByCondition(wechatRecord.getFormusername(),wechatRecord.getTousername(),msgId);
				if(red==null){
					wechatRecordService.save(wechatRecord);
				}

				FileKit.createDir(imgDir, false);
				String imgUrl = wechatMeta.getBase_uri() + "/webwxgetmsgimg?MsgID=" + msgId + "&skey=" + wechatMeta.getSkey() + "&type=slave";
				HttpRequest.get(imgUrl).header("Cookie", wechatMeta.getCookie()).receive(new File(imgDir + "/" + msgId+".jpg"));

				//				webwxsendmsg(wechatMeta, "二蛋还不支持图片呢", msg.getString("FromUserName"));
			} else if (msgType == 34) {
//				webwxsendmsg(wechatMeta, "二蛋还不支持语音呢", msg.getString("FromUserName"));
			} else if (msgType == 42) {
				LOGGER.info(name + " 给你发送了一张名片:");
				LOGGER.info("=========================");
			}
		}
	}
	
	/**
	 * 发送消息
	 */
	private void webwxsendmsg(WechatMeta meta, String content, String to) {
		String url = meta.getBase_uri() + "/webwxsendmsg?lang=zh_CN&pass_ticket=" + meta.getPass_ticket();
		JSONObject body = new JSONObject();

		String clientMsgId = DateKit.getCurrentUnixTime() + StringKit.getRandomNumber(5);
		JSONObject Msg = new JSONObject();
		Msg.put("Type", 1);
		Msg.put("Content", content);
		Msg.put("FromUserName", meta.getUser().getString("UserName"));
		Msg.put("ToUserName", to);
		Msg.put("LocalID", clientMsgId);
		Msg.put("ClientMsgId", clientMsgId);

		body.put("BaseRequest", meta.getBaseRequest());
		body.put("Msg", Msg);

		HttpRequest request = HttpRequest.post(url).contentType("application/json;charset=utf-8")
				.header("Cookie", meta.getCookie()).send(body.toString());

		LOGGER.info("发送消息...");
		LOGGER.debug("" + request);
		request.body();
		request.disconnect();
	}

	public String getNickNameByName(WechatMeta wechatMeta,String name) {
		String nameName = "这个人物名字未知";
		String curUserName=wechatMeta.getUser().get("UserName").toString();
		curUserName=curUserName.substring(1,curUserName.length()-1);
		if(curUserName.equals(name)){
			String curNickName=wechatMeta.getUser().get("NickName").toString();
			return curNickName.substring(1,curNickName.length()-1);
		}
		String s = jedis.get(wechatMeta.getWxuin().toString());
		JSONObject webcontact =JSONKit.parseObject(jedis.get(wechatMeta.getWxuin().toString()));
		if(webcontact!=null&&webcontact.get("groupChatList")!=null) {
			JSONArray groupChatList=(JSONArray)webcontact.get("groupChatList");
			for (int i = 0, len = groupChatList.size(); i < len; i++) {
				JSONObject groupChat =groupChatList.get(i).asJSONObject();
				if (groupChat.getString("UserName").equals(name)) {
					nameName=groupChat.getString("NickName");
					return nameName;
				}
			}
		}
		if(webcontact!=null&&webcontact.get("contactList")!=null) {
			JSONArray contactList=(JSONArray)webcontact.get("contactList");
			for (int i = 0, len = contactList.size(); i < len; i++) {
				JSONObject contact =contactList.get(i).asJSONObject();
				if (contact.getString("UserName").equals(name)) {
					nameName=contact.getString("NickName");
					return nameName;
				}
			}
		}
		if(webcontact!=null&&webcontact.get("memberList")!=null) {
			JSONArray memberList=(JSONArray)webcontact.get("memberList");
			for (int i = 0, len = memberList.size(); i < len; i++) {
				JSONObject member =memberList.get(i).asJSONObject();
				if (member.getString("UserName").equals(name)) {
					nameName=member.getString("NickName");
					return nameName;
				}
			}
		}
		return nameName;
	}


	private String getUserRemarkName(WechatMeta wechatMeta,String id) {
        String name = "这个人物名字未知";
        String s = jedis.get(wechatMeta.getWxuin().toString());
        WechatContact contact =JSONKit.parse(jedis.get(wechatMeta.getWxuin().toString()),WechatContact.class);
        if(contact!=null&&contact.getMemberList()!=null) {
            for (int i = 0, len = contact.getMemberList().size(); i < len; i++) {
                JSONObject member = contact.getMemberList().get(i).asJSONObject();
                if (member.getString("UserName").equals(id)) {
                    if (StringKit.isNotBlank(member.getString("RemarkName"))) {
                        name = member.getString("RemarkName");
                    } else {
                        name = member.getString("NickName");
                    }
                    return name;
                }
            }
        }
        return name;
    }
	
	@Override
	public JSONObject webwxsync(WechatMeta meta){
		
		String url = meta.getBase_uri() + "/webwxsync?skey=" + meta.getSkey() + "&sid=" + meta.getWxsid();
		
		JSONObject body = new JSONObject();
		body.put("BaseRequest", meta.getBaseRequest());
		body.put("SyncKey", meta.getSyncKeyWord());
		body.put("rr", DateKit.getCurrentUnixTime());

		HttpRequest request = HttpRequest.post(url).contentType("application/json;charset=utf-8")
				.header("Cookie", meta.getCookie()).send(body.toString());
		
		LOGGER.debug(request.toString());
		String res = request.body();
		request.disconnect();

		if (StringKit.isBlank(res)) {
			throw new WechatException("同步syncKey失败");
		}
		
		JSONObject jsonObject = JSONKit.parseObject(res);
		JSONObject BaseResponse = jsonObject.get("BaseResponse").asJSONObject();
		if (null != BaseResponse) {
			int ret = BaseResponse.getInt("Ret", -1);
			if (ret == 0) {
				meta.setSyncKeyWord(jsonObject.get("SyncKey").asJSONObject());
				StringBuffer synckey = new StringBuffer();
				JSONArray list = meta.getSyncKeyWord().get("List").asArray();
				for (int i = 0, len = list.size(); i < len; i++) {
					JSONObject item = list.get(i).asJSONObject();
					synckey.append("|" + item.getInt("Key", 0) + "_" + item.getInt("Val", 0));
				}
				meta.setSynckey(synckey.substring(1));
				return jsonObject;
			}
		}
		return null;
	}

	/**
	 * 发送消息
	 *
	 * @param meta
	 * @return
	 */
	@Override
	public void wxSendMsg(WechatMeta meta, String content, String to) {
		webwxsendmsg(meta , content, to);
	}

	/**
	 * 创建群聊
	 *
	 * @param meta
	 * @param topic
	 * @param memberCount
	 * @param jsonArray
	 * @return
	 */
	@Override
	public void createChatRoom(WechatMeta meta, String topic, String memberCount, JSONArray jsonArray) {
		String url = meta.getBase_uri() + "/webwxcreatechatroom?r="+DateKit.getCurrentUnixTime()+"&lang=zh_CN&pass_ticket=" + meta.getPass_ticket();
		JSONObject body = new JSONObject();
		body.put("BaseRequest", meta.getBaseRequest());
		body.put("Topic", topic);
		body.put("MemberCount", Integer.parseInt(memberCount));
		body.put("MemberList", jsonArray);
        HttpRequest request = null;
        String res = "";
        try{
             request = HttpRequest
                    .post(url, true, "r", DateKit.getCurrentUnixTime() + StringKit.getRandomNumber(5), "skey",
                            meta.getSkey(), "uin", meta.getWxuin(), "sid", meta.getWxsid(), "deviceid",
                            meta.getDeviceId(), "synckey", meta.getSynckey(), "_", System.currentTimeMillis())
                    .header("Cookie", meta.getCookie()).send(body.toString());
            LOGGER.info("创建群聊...");
			Thread.sleep(500);
            res = request.body();
        }catch (Exception e){
            LOGGER.info(e.getMessage());
        }finally {
            if(request!=null){
                request.disconnect();
            }
        }
        //置顶群聊
        if (StringKit.isNotBlank(res)) {
            JSONObject jsonObject=JSONKit.parseObject(res);
            System.out.println(jsonObject.get("ChatRoomName"));
            String code = jsonObject.get("ChatRoomName").toString();
            if (null != code) {
                JSONObject msg = new JSONObject();
                msg.put("CmdId",3);
                msg.put("OP",1);
                msg.put("RemarkName","");
                msg.put("UserName",code);
                String topUrl = meta.getBase_uri() + "/webwxoplog?r="+DateKit.getCurrentUnixTime()+"&lang=zh_CN&pass_ticket=" + meta.getPass_ticket();
                HttpRequest req = null;
                try{
                     req = HttpRequest
                            .post(topUrl, true, "r", DateKit.getCurrentUnixTime() + StringKit.getRandomNumber(5), "skey",
                                    meta.getSkey(), "uin", meta.getWxuin(), "sid", meta.getWxsid(), "deviceid",
                                    meta.getDeviceId(), "synckey", meta.getSynckey(), "_", System.currentTimeMillis())
                            .header("Cookie", meta.getCookie()).send(msg.toString());
					Thread.sleep(500);
					 res=req.body();
                     LOGGER.info("置顶群操作");
                }catch (Exception e){
                    LOGGER.info("置顶群操作失败");
                }finally {
                    req.disconnect();
                }

                }
            }
	}

    /**
     * 追加群成员
     *
     * @param meta
     * @param chatRoomName
     * @param username
     */
    @Override
    public void addToChatRoom(WechatMeta meta, String chatRoomName, String username) {
        String url = meta.getBase_uri() + "/webwxupdatechatroom?fun=addmember&lang=zh_CN&pass_ticket=" + meta.getPass_ticket();
        JSONObject body = new JSONObject();
        String clientMsgId = DateKit.getCurrentUnixTime() + StringKit.getRandomNumber(5);
        body.put("AddMemberList", username);
        body.put("ChatRoomName", chatRoomName);
        body.put("BaseRequest", meta.getBaseRequest());
        HttpRequest request = HttpRequest.post(url).contentType("application/json;charset=utf-8")
                .header("Cookie", meta.getCookie()).send(body.toString());

        LOGGER.info("追加群成员...");
        LOGGER.debug("" + request);
        request.body();
        request.disconnect();
    }

    /**
     * 批量获取群成员
     *
     * @param meta
     * @param count
     * @param jsonArray
     */
    @Override
    public JSONObject batchGetContact(WechatMeta meta, String count, JSONArray jsonArray) {
        String url = meta.getBase_uri() + "/webwxbatchgetcontact?type=ex&r="+DateKit.getCurrentUnixTime()+"&lang=zh_CN&pass_ticket=" + meta.getPass_ticket();
        JSONObject body = new JSONObject();
        body.put("Count", count);
        body.put("List",jsonArray);
		body.put("BaseRequest", meta.getBaseRequest());
        HttpRequest request = null;
        String res = "";
        try{
			  request = HttpRequest.post(url).contentType("application/json;charset=utf-8")
					.header("Cookie", meta.getCookie()).send(body.toString());
            res = request.body();
        }catch (Exception e){
            LOGGER.info(e.getMessage());
        }finally {
            if(request!=null){
                request.disconnect();
            }
        }
        return JSONKit.parseObject(res);
    }

	/**
	 * 更新群成员
	 *
	 */
	@Override
	public void updateChatRoom(WechatMeta meta, String chatRoomName, String username) {
		String url = meta.getBase_uri() + "/webwxupdatechatroom?fun=delmember&r="+DateKit.getCurrentUnixTime()+"&lang=zh_CN&pass_ticket=" + meta.getPass_ticket();
		JSONObject body = new JSONObject();
		body.put("ChatRoomName", chatRoomName);
		body.put("DelMemberList",username);
		body.put("BaseRequest", meta.getBaseRequest());
		HttpRequest request = null;
		String res = "";
		try{
			request = HttpRequest.post(url).contentType("application/json;charset=utf-8")
					.header("Cookie", meta.getCookie()).send(body.toString());
			/*request = HttpRequest
					.post(url, true, "r", DateKit.getCurrentUnixTime() + StringKit.getRandomNumber(5), "skey",
							meta.getSkey(), "uin", meta.getWxuin(), "sid", meta.getWxsid(), "deviceid",
							meta.getDeviceId(), "synckey", meta.getSynckey(), "_", System.currentTimeMillis())
					.header("Cookie", meta.getCookie()).send(body.toString());*/
			LOGGER.info("更新群成员...");
			res = request.body();
		}catch (Exception e){
			LOGGER.info(e.getMessage());
		}finally {
			if(request!=null){
				request.disconnect();
			}
		}
	}

	public static File   inputstreamtofile(InputStream ins,File f) {
		try {
			OutputStream os = new FileOutputStream(f);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while((bytesRead = ins.read(buffer,0,8192)) != -1){
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		 return f;
	}

	/**
	 * 上传图片
	 * @return
	 */
	@Override
	public JSONObject upLoadImg(WechatMeta meta,File file,String formusername,String tousername) throws IOException {
		String url ="https://file.wx.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json&lang=zh_CN&r="+DateKit.getCurrentUnixTime();
		//File f=new File("F://2.jpg");
		JSONObject jsonObject= new JSONObject();
		jsonObject.put("BaseRequest",meta.getBaseRequest());
		jsonObject.put("UploadType",2);
		jsonObject.put("TotalLen",file.length());
		jsonObject.put("StartPos",0);
		jsonObject.put("DataLen",file.length());
		jsonObject.put("MediaType",4);
		jsonObject.put("ClientMediaId",new Date().getTime());
		jsonObject.put("FromUserName",formusername);
		jsonObject.put("ToUserName",tousername);
		jsonObject.put("FileMd5",getMd5ByFile(file));
		String webwx_data_ticket=getWebwx_data_ticket(meta.getCookie());
		MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,"----WebKitFormBoundary5FAunQIZoODX7YRt", Charset.defaultCharset());
		multipartEntity.addPart("uploadmediarequest",new StringBody(jsonObject.toString(), Charset.forName("UTF-8")));
		multipartEntity.addPart("webwx_data_ticket",new StringBody(webwx_data_ticket, Charset.forName("UTF-8")));
		multipartEntity.addPart("pass_ticket",new StringBody(meta.getPass_ticket(), Charset.forName("UTF-8")));
		multipartEntity.addPart("size",new StringBody(file.length()+"", Charset.forName("UTF-8")));
		multipartEntity.addPart("type",new StringBody("image/jpeg", Charset.forName("UTF-8")));
		multipartEntity.addPart("mediatype",new StringBody("pic", Charset.forName("UTF-8")));
		multipartEntity.addPart("id",new StringBody("WU_FILE_0", Charset.forName("UTF-8")));
		multipartEntity.addPart("name",new StringBody(file.getName(), Charset.forName("UTF-8")));
		multipartEntity.addPart("filename",new FileBody(file,"image/jpeg"));
		HttpPost request = new HttpPost(url);
		request.setEntity(multipartEntity);
		request.addHeader("Content-Type","multipart/form-data; boundary=----WebKitFormBoundary5FAunQIZoODX7YRt");

		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpResponse response =httpClient.execute(request);
		InputStream is = response.getEntity().getContent();
		BufferedReader in = new BufferedReader(new InputStreamReader(is));
		StringBuffer buffer = new StringBuffer();
		String line = "";
		while ((line = in.readLine()) != null) {
			buffer.append(line);
		}
		//f.delete();
	return JSONKit.parseObject(buffer.toString());
	}


	public  String getWebwx_data_ticket (String cookie){
		String str="";
		String[] datas=cookie.split(";");
		for(int i=0;i<datas.length;i++){
			String temp=datas[i];
			String[] tempdatas=temp.split("=");
			if(tempdatas[0].equals("webwx_data_ticket")){
				str=tempdatas[1];
				break;
			}
		}
		return  str;
	}



	/**
	 * 发送图片
	 * @param meta
	 * @param mediaId
	 * @param to
	 */
    @Override
	public void wxSendMsgImg(WechatMeta meta, String mediaId, String to) throws IOException {
		String url = meta.getBase_uri() + "/webwxsendmsgimg?fun=async&f=json&lang=zh_CN&pass_ticket=" + meta.getPass_ticket();
		JSONObject body = new JSONObject();

		String clientMsgId = DateKit.getCurrentUnixTime() + StringKit.getRandomNumber(5);
		JSONObject Msg = new JSONObject();
		Msg.put("Type", 3);
		Msg.put("Content", "");
		Msg.put("MediaId", mediaId);
		Msg.put("FromUserName", meta.getUser().getString("UserName"));
		Msg.put("ToUserName", to);
		Msg.put("LocalID", clientMsgId);
		Msg.put("ClientMsgId", clientMsgId);

		body.put("BaseRequest", meta.getBaseRequest());
		body.put("Msg", Msg);
		body.put("Scene", 0);

		HttpRequest request = HttpRequest.post(url).contentType("application/json;charset=utf-8")
				.header("Cookie", meta.getCookie()).send(body.toString());

		LOGGER.info("发送消息...");
		LOGGER.debug("" + request);
		request.body();
		request.disconnect();
	}


}
